package com.lebron.kotlin.http

import com.lebron.kotlin.BaseApplication
import com.lebron.kotlin.BuildConfig
import okhttp3.Cache
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.io.File

/**
 * @Author lebron
 * @Date 18-7-26-下午1:53
 * 网络请求管理类
 */
object DouBanApiManager {
    private const val DEFAULT_CACHE_SIZE: Long = 1024 * 1024 * 20

    private fun getOkHttpClient(): OkHttpClient {
        val loggingInterceptor = HttpLoggingInterceptor()
        loggingInterceptor.level = if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY else HttpLoggingInterceptor.Level.NONE
        val cacheFile = File(BaseApplication.instance.applicationContext?.cacheDir, "response")

        return OkHttpClient.Builder()
                .cache(Cache(cacheFile, DEFAULT_CACHE_SIZE))
                .addInterceptor(loggingInterceptor)
                .build()
    }

    private fun getDefaultRetrofit(baseUrl: String): Retrofit? {

        return Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(getOkHttpClient())
                .addConverterFactory(GsonConverterFactory.create())/*使用Gson作为数据转换器*/
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())/*使用RxJava2作为回调适配器*/
                .build()
    }

    fun <T : Any?> createService(baseUrl: String, serviceCLass:Class<T>) : T? {
        return getDefaultRetrofit(baseUrl)?.create(serviceCLass)
    }
}


